package com.alibaba.dongbao.controller.ums;

import com.alibaba.dongbao.base.result.Result;
import com.alibaba.dongbao.dto.UserDTO;
import com.alibaba.dongbao.entity.User;
import com.alibaba.dongbao.service.UserService;
import com.alibaba.dongbao.utils.annotations.LoginToken;
import com.baomidou.kaptcha.Kaptcha;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Mr.ZJW
 * @Date: 2022-04-06 17:08
 * @Description: 用户相关接口
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private Kaptcha kaptcha;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserService memberService;

    /**
     * @Author: Mr.ZJW
     * @Description: 用户注册
     * @Date: 2022/4/6 17:09
     **/
    @PostMapping("/registerUser")
    public Result registerUser(@RequestBody @Valid User member) {
        return memberService.registerUser(member);
    }

    /**
     * @Author: Mr.ZJW
     * @Description: 获取验证码
     * @Date: 2022/4/27 11:21
     **/
    @GetMapping("/getCaptcha")
    public void getCaptcha() {
        //生成验证码
        String render = kaptcha.render();
        //验证码存放到redis
        redisTemplate.opsForValue().set("code", render);
        //设置验证码过期时间60秒
        redisTemplate.expire("code", 60, TimeUnit.SECONDS);
    }

    /**
     * @param [memberDTO = 登录封装参数类]
     * @Author: Mr.ZJW
     * @Description: 登录接口
     * @Date: 2022/5/16 9:35
    **/
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO memberDTO) {
        log.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "-登录接口参数:{}", new Gson().toJson(memberDTO));
        return memberService.login(memberDTO);
    }

    /**
     * @Author: Mr.ZJW
     * @Description: 修改用户信息
     * @Date: 2022/4/8 16:10
     **/
    @PostMapping("/modifyUser")
    @LoginToken
    public Result modifyUser(@RequestBody User user) {
        return memberService.modifyUser(user);
    }

    /**
     * @Author: Mr.ZJW
     * @Description: 查询用户列表
     * @Date: 2022/4/8 13:58
     **/
    @GetMapping("/queryUserList")
    public Result queryUserList(@RequestBody UserDTO member, Page page) {
        return Result.success(memberService.queryUserList(page, member));
    }

    /**
     * @param [userDTO] 修改密码封装实体类
     * @Author: Mr.ZJW
     * @Description: 用户修改密码
     * @Date: 2022/6/6 9:08
    **/
    @LoginToken
    @PostMapping("/userModifyPassword")
    public Result userModifyPassword(@RequestBody UserDTO userDTO){
        return memberService.userModifyPassword(userDTO);
    }

}
